package com.example.rbacmanage.controller;

import com.example.rbacmanage.annotation.CurrentUser;
import com.example.rbacmanage.common.Result;
import com.example.rbacmanage.entity.Chat;
import com.example.rbacmanage.entity.User;
import com.example.rbacmanage.service.ChatService;
import com.example.rbacmanage.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 聊天前端控制层
 *
 * @author zmd
 */
@RestController
@RequestMapping("/app/chat")
public class ChatAppController {
    @Autowired
    private ChatService chatService;
    @Autowired
    private UserService userService;

    /**
     * 分页查询列表
     */
    @GetMapping(value = "/page")
    public Result page(@CurrentUser Long userId, Chat entity) {
        entity.setMinappUserId(userId);
        if (entity.getShopId() != null){
            User user = new User();
//            user.setShopId(entity.getShopId());
            List<User> userList = userService.getAll(user);
            List<Long> userIds = userList.stream().map(User::getId).toList();
            entity.setSystemUserIds(userIds);
        }
        PageInfo pageInfo = chatService.getPage(entity);
        List<Chat> chats = pageInfo.getList();
        if (chats != null){
            for (Chat chat : chats){
                if (chat.getRead().equals("1")){
                    continue;
                }
                Chat update = new Chat();
                update.setRead("1");
                update.setId(chat.getId());
                chatService.update(update);
            }
        }
        return Result.success(pageInfo);
    }

    /**
     * 查询列表
     */
    @GetMapping(value = "/list")
    public Result list(Chat entity) {
        return Result.success(chatService.getAll(entity));
    }

    /**
     * 根据id获取详情
     */
    @GetMapping(value = "/{id}")
    public Result getById(@PathVariable(value = "id") Long id) {
        return Result.success(chatService.getById(id));
    }

    /**
     * 新增
     */
    public Result save(@RequestBody Chat entity) {
         chatService.save(entity);
        return Result.success();
    }

    /**
     * 更新
     */
    @PutMapping(value = "/update")
    public Result update(@RequestBody Chat entity) {
        chatService.update(entity);
        return Result.success();
    }

    /**
     * 删除
     */
    @DeleteMapping(value = "/remove")
    public Result deleteByIds(@RequestBody Long[] ids) {
        chatService.remove(ids);
        return Result.success();
    }

    @GetMapping(value = "/noReadCount")
    public Result getCurrentUserNoReadCount(@CurrentUser Long userId,Chat entity) {
        entity.setMinappUserId(userId);
        entity.setRead("0");
        entity.setSendRole(0);
        return Result.success(chatService.getCount(entity));
    }
}
